package com.huiyeji.dynamic.core;

import com.huiyeji.dynamic.core.exception.DynamicStatementExecuteException;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Huiyeji
 */
public class PluginObject extends DynamicObject {

    private PluginEngine engine;

    public PluginObject(String name,List<String> initializeStatements, Map<String,List<String>> methodStatements, DynamicContext parentContext) {
        super(new DynamicObjectInfo(name,"[Plugin]-"+name), null);
        new PluginEngine(name,initializeStatements,methodStatements,parentContext,this);
    }

    protected void setEngine(PluginEngine engine){
        this.engine = engine;
    }

    @Override
    public Object invoke(String methodName, Object... args) throws InvocationTargetException, IllegalAccessException {
        DynamicResult result = engine.processMethod(methodName, args);
        if (result == null){
            return null;
        }
        if (!result.isSuccess()){
            DynamicErrorResult errorResult = (DynamicErrorResult) result;
            throw new DynamicStatementExecuteException("Plugin 【"+getDynamicObjectName()+"】 method 【"+methodName+"】 Process Error : "+errorResult.getExceptionMessage());
        }

        return result.getReturnData().get("data");
    }

    protected void interrupt(){
        engine.interrupt();
    }

    protected boolean haveMethod(String methodName){
        return engine.haveMethod(methodName);
    }
}
